{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "     fun: 1.0028485230674278\n",
       "     jac: array([-9.54791801e-07,  1.67643677e-05,  1.12132525e-05, -1.71418435e-05])\n",
       " message: 'Optimization terminated successfully.'\n",
       "    nfev: 3970\n",
       "     nit: 64\n",
       " success: True\n",
       "       x: array([1.00574233, 0.19922074, 1.40038485, 9.99905622])"
      ]
     },
     "execution_count": 4,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "from scipy.optimize import differential_evolution\n",
    "\n",
    "from sklearn.metrics import r2_score\n",
    "\n",
    "import numpy as np\n",
    "\n",
    "A, B, C, D = 1, .2, 1.4, 10\n",
    "\n",
    "\n",
    "def Fn(t, A, B, C, D):\n",
    "    return A*np.exp(-B*t)*np.sin(C*t) + D\n",
    "\n",
    "np.random.seed(234567)\n",
    "n_pts = 1000\n",
    "t = np.linspace(1,20,n_pts) + .3*np.random.rand(n_pts)\n",
    "y_true = Fn(t, A, B, C, D)\n",
    "y_meas = y_true + .11*(0.5 - np.random.rand(n_pts))\n",
    "\n",
    "def func(parameters, *data):\n",
    "    A, B, C, D = parameters\n",
    "    Fn, t, Y = data\n",
    "    \n",
    "    return np.linalg.norm(Fn(t,A,B,C,D)-Y)\n",
    "\n",
    "bounds=([0.01, 100],\n",
    "        [ -10, 10],\n",
    "        [0.01, 10],\n",
    "        [-100, 100])\n",
    "\n",
    "args = (Fn, t, y_meas)\n",
    "\n",
    "DE_result = differential_evolution(func, bounds, args=args)\n",
    "\n",
    "DE_result"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "0.9998993761732811"
      ]
     },
     "execution_count": 5,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "y_DE_fit = Fn(t, *DE_result.x)\n",
    "\n",
    "\n",
    "r2_score(y_true, y_DE_fit)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.5"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
